/**
 *Copyright(c) HNA SYSTEMS Co., LTD
 *
 *@date 2013-7-10
 * 	
 *Original Author: 郑兴(zhengxing)
 *
 *ChangeLog
 *
 */
package com.hnas.core.util;

import java.util.ArrayList;
import java.util.List;
//import java.util.regex.MatchResult;

import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcherInput;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

import com.hnas.core.exception.CommonException;



/**
 * @author 郑兴(zhengxing)
 *
 */
public class StringUtil {
	/**
	 * <pre>
	 * 字符串为空
	 * </pre>
	 * 
	 * @Auther 郑兴(zhengxing)
	 * @Date 2013-7-10
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return null == str || str.trim().equals("");
	}
	
	/**
	 * <pre>
	 * 字符串不为空
	 * </pre>
	 * 
	 * @Auther 郑兴(zhengxing)
	 * @Date 2013-7-10
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(String str) {
		return null != str && !str.trim().equals("");
	}
	

	/**
	 * 正着表达式的匹配
	 * 
	 * @param content
	 * @param reg
	 * @param groups
	 * @return
	 * @throws CommonException
	 */
	public static boolean patternContentByReg(String content,  String reg)
			throws CommonException {

		List list = new ArrayList();

		if (content == null || reg == null) {
			throw new CommonException("参数为空");
		}

		org.apache.oro.text.regex.Pattern pattern = null;

		Perl5Matcher matcher = new Perl5Matcher();
		PatternCompiler c = new Perl5Compiler();
		PatternMatcherInput input = new PatternMatcherInput(content);
		try {
			pattern = c.compile(reg);
			// 使用find()方法查找第一个匹配的对象
			if (matcher.contains(input, pattern)) {
				MatchResult result = matcher.getMatch(); 
				return true;
			}
			// 继续查找下一个匹配对象


		} catch (Exception e) {
			// TODO Auto-generated catch block
			return false;
		}

		return false;
	}


	public static void checkIDcard(String iDcardNum)
			throws CommonException {

		if (iDcardNum == null || iDcardNum.length() == 0) {
			throw new CommonException("身份证号码长度为0");
		}
		if(iDcardNum.trim().length()!=15 && iDcardNum.trim().length()!=18)
		{
			throw new CommonException("身份证号码长度必需为15位或18位!"+iDcardNum);
		}
		
		//String reg1 = "^[1-9][0-9]{5}[0-9]{4}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$";//  18位
		//"地址码(国内34省+国外"91")"+"年(1900-3000)"+"月日"+"顺序码"+"校验码"
		String city = "(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|71|8[1-2])";	//34省区划代码
		String reg1 = "^(("+city+"\\d{4})|(91\\d{4}))"+"(19\\d{2}|2\\d{3}|3000)"+"((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))"+"[0-9]{3}"+"[0-9Xx]$";//  18位

		//String reg2 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";//15位
		String reg2 = "^(("+city+"\\d{4})|(91\\d{4}))"+"\\d{2}"+"((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))"+"\\d{3}$";//15位

		if (!(patternContentByReg(iDcardNum, reg2)|| patternContentByReg(iDcardNum, reg1))){
			throw new CommonException("身份证号码:"+iDcardNum+"格式不正确！");
		}
		
		//by qc_zhong
		if(iDcardNum.length() == 18){
			int []Wi = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1};	//权值
			char []Ai = {'1','0','X','9','8','7','6','5','4','3','2'};  //校验结果匹配
			String idNum = iDcardNum;
			
			
			if(idNum.charAt(17)=='x')
				idNum = iDcardNum.replace('x', 'X');
			
			char checkDigit = idNum.charAt(17);	//校验码
			int sum = 0;	//本体码级数之和
			
			//计算级数之和
			for(int i=0;i<idNum.length()-1;i++)
				sum += (idNum.charAt(i)-0x30)*Wi[i];
			//获取校验码字符值
			char checkDigitResult = Ai[sum%11];
			
			//对比校验码
			if(checkDigitResult != checkDigit){
				throw new CommonException("您输入的身份证号码校验失败，请重新检查并输入!"+iDcardNum);
			}
		}	
	}

	public static void checkCard(String cardNum)
			throws CommonException {

		if (cardNum == null || cardNum.length() == 0) {
			throw new CommonException("证件号码长度位0");
		}

		String reg1 = "^[a-z A-Z0-9\\-\\.()]{2,30}$";// 18位



		if (!patternContentByReg(cardNum, reg1))
		{
			throw new CommonException("证件号码"+cardNum+"格式不正确！"+cardNum);
		}
	}

	public static void checkAddress(String address)
			throws CommonException {
		
		if (address == null || address.length() == 0) {
			throw new CommonException("地址中的信息必填！");
		}
		if(address.trim().length()>35)
			throw new CommonException("地址中各项的长度不能超过35个字符！");
		
		String reg1 = "^[a-z A-Z0-9]{2,35}$";// 		
		
		
		if (!patternContentByReg(address, reg1))
		{
			throw new CommonException("地址信息格式不正确，只能为数字、字母、空格！"+address);
		}
	}
	
	public static void checkPhoneNo(String phoneNum)
			throws CommonException {

		if (phoneNum == null || phoneNum.length() == 0 || phoneNum.equals("")) {
			throw new CommonException("联系电话为空");
		}
		phoneNum = phoneNum.trim();

		String reg1 = "^[0-9-]+$";



		if (!patternContentByReg(phoneNum, reg1))
		{
			throw new CommonException("联系电话"+phoneNum+"格式不正确！"+phoneNum);
		}
		if (phoneNum.startsWith("1") && phoneNum.length()!=11){
			throw new CommonException("手机号码位数不对！"+phoneNum);
		}

	}
	public static boolean checkPassengerName(String src) throws CommonException {

		try {
		
				//当前支持全部GBK字符
				/**//* 判断是否含有GBK以外的特殊字符 */
				/*boolean isGBK(String s) throws UnsupportedEncodingException
				{
				    if(s.equals(new String(s.getBytes("gbk"))))
				        return true;
				    else
				        return false;
				}*/
				if (null==src)
					throw new CommonException("旅客姓名为空！"+src);
				  if (src.length() >= 28)
			        {
					  throw new CommonException("旅客姓名不能超过28个字符！"+src);
			        }
				 if (src.indexOf("/") < 0 && src.indexOf(" ") > 0)
					 throw new CommonException("旅客姓名中不能含有空格！"+src);
				 
				if(!src.equals(new String(src.getBytes("GBK"),"GBK"))) //GB2312
					throw new CommonException("旅客姓名只能为GBK字符！"+src);
				/*byte[] srcByte = src.getBytes("GB2312");
				for (int i = 0; i < srcByte.length; i++) {
					if (srcByte[i] < 0) {
						if (srcByte[i] < -80) // 256-176=80
						{
							return false;
						} else if (srcByte[i + 1] < -96) // 256-160=96
						{
							return false;
						} else {
							i++;
						}
					} else if (srcByte[i] == 63) {
						return false;
					}
				}*/
				//字母后面须为 字母 空格 斜杠
				boolean hasLetter = false;
				for (int i=0;i<src.length();i++){
					char c = src.charAt( i );
					if (Character.isDigit( c ))
						throw new CommonException("旅客姓名中不能包含数字！"+src);
					if ((c>='a' && c<='z') || (c>='A' && c<='Z'))
						hasLetter = true;
					if (hasLetter){//只允许字母和空格
						if (c!=' ' && c!='/' && !(c>='a' && c<='z') && !(c>='A' && c<='Z'))
							throw new CommonException("字母后面不能为汉字！"+src);
					}
				}
				return true;
			
		} catch (Exception e) {
//			e.printStackTrace();
			throw new CommonException(e);
		}
//		return false;
	}
	
	/**
	 * <pre>
	 * 字符串转换成数组.
	 * </pre>
	 * @auther 许亚明（yam-xu）
	 * 2013-9-4
	 * @param str
	 * @return String[]
	 */
	public static String[] stringToArray(String str) {
		if (StringUtil.isNotEmpty(str)) {
			String[] resultArray = str.split("/");
			return resultArray;
		}
		return null;
	}
	public static String getChangeString(String mrchID){
		String mrchIDStr="";
		if(StringUtil.isNotEmpty(mrchID)){
			  String[] mrchIDs=mrchID.split(",");
			  for(String id:mrchIDs){
				  mrchIDStr=mrchIDStr+",'"+id+"'";
			  }
			  mrchIDStr=mrchIDStr.substring(1);
		}
		return mrchIDStr;
	}
	public static boolean checkInside(long[] ids,long id){
		for (long id1:ids){
			if (id1==id)
				return true;
		}
		return false;
	}
	
	/**
     * 查找字符串pattern在str中第一次出现的位置
     * 
     * @param str
     * @param pattern
     * @return
     */
    public static int firstIndexOf(String str, String pattern) {
        for (int i = 0; i < (str.length() - pattern.length()); i++) {
            int j = 0;
            while (j < pattern.length()) {
                if (str.charAt(i + j) != pattern.charAt(j))
                    break;
                j++;
            }
            if (j == pattern.length())
                return i;
        }
        return -1;
    }
    
//	public static void checkAddress(DTOAddress address)
//			throws CommonException {
//		checkAddress(address.getAddress());
//		checkAddress(address.getCity());
//		checkAddress(address.getCountry());
//		checkAddress(address.getState());
//		checkAddress(address.getZip());
//	}

    public static String strDrim(String s){
    	String result = "";  
        if(null!=s && !"".equals(s)){  
        	result = s.replaceAll("^[　*| *]*","").replaceAll("[　*| *]*$","").trim(); 
        }  
        return result; 
    }
}
